/**
 * @(#)WeiboUserServiceImpl.java 2017年2月21日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.service.impl;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.dao.INewClientInfoDao;
import org.jsbd.boss.dao.INewWeiboUserDao;
import org.jsbd.boss.dao.IWeiboUserDAO;
import org.jsbd.boss.domian.channel.*;
import org.jsbd.boss.enums.LoginTypeEnum;
import org.jsbd.boss.service.ClientManager;
import org.jsbd.boss.service.ISimulatorLogService;
import org.jsbd.boss.service.IUserClientInfoService;
import org.jsbd.boss.task.ExtraParamOssUploadTask;
import org.jsbd.boss.util.BeanCopierUtil;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.DateUtil;
import org.springframework.stereotype.Service;

import edu.hziee.common.queue.DelayExecuteBuffer;

/**
 * 微博用户服务
 *
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
@Service("weiboUserService")
public class WeiboUserServiceImpl extends ThirdLoginAdapterHandler<WeiboUser> {

    @Resource
    private IWeiboUserDAO weiboUserDAO;

    @Resource
    private INewWeiboUserDao newWeiboUserDao;

    @Resource
    private INewClientInfoDao newClientInfoDao;

    @Resource
    private RedisClient redisClient;

    /* (non-Javadoc)
     * @see org.jsbd.boss.service.impl.ThirdLoginAdapterHandler#init()
     */
    @Override
    public boolean init() {
        loginIndexKey = CacheKey.NEW_CLIENT_WEIBO_USER_INDEX;
        loginType = LoginTypeEnum.WEIBO;
        queueKey = CacheKey.NEW_CLIENT_WEIBO_USER_QUEUE;
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.jsbd.boss.service.impl.AbsThirdUserServiceImpl#selectUserList(java
     * .lang.Integer, java.lang.Integer, java.lang.Integer)
     */
    @Override
    public List<WeiboUser> selectUserList(ThirdUserQueryVo queryVo) {
        long startTime = System.currentTimeMillis();
        Integer start = 0;
        Integer provinceId = queryVo.getProvinceId();
        Integer carrier = queryVo.getCarrier();
        String indexKey = getIndexKey(queryVo.getBase(), queryVo.getApkId(), provinceId, carrier);
        Object indexObj = redisClient.get(indexKey);
        if (indexObj != null) {
            start = Integer.parseInt(indexObj.toString());
        }
//        queryVo.setProvinceId(provinceId);
        queryVo.setStart(start);
        queryVo.setLength(queryVo.getLength());
        List<WeiboUser> weiboUsers = newWeiboUserDao.selectUserList2(queryVo);
        if(weiboUsers.isEmpty()){
            start = 0;
            LOGGER.warn("apk {} base {} 省份{} 登录类型 {} 获取到的数据大小 {} 时间 {}", new Object[]{queryVo.getApkId(), queryVo.getBase(), provinceId, loginType.getName(), 0, System.currentTimeMillis() - startTime});
        }else{
            start = weiboUsers.get(weiboUsers.size() -1).getId();
        }
        redisClient.put(indexKey, start);
        Iterator<WeiboUser> iterator = weiboUsers.iterator();
        while (iterator.hasNext()) {
            WeiboUser weiboUser = iterator.next();
            String userName = weiboUser.getUserName();
            String password = weiboUser.getPassword();
            String imsi = weiboUser.getImsi();
            QueryUserClientVo queryUserClientVo = new QueryUserClientVo();
            queryUserClientVo.setCarrier(carrier);
            queryUserClientVo.setProvince(provinceId);
            queryUserClientVo.setImsi(imsi);
            UserClientInfo userClientInfo = newClientInfoDao.selectClientInfo(queryUserClientVo);
            if(userClientInfo == null){
                userClientInfo = selectRandomUser(userName, carrier, provinceId);
                if(userClientInfo != null){
                    BeanCopierUtil.UserClient2ThirdUserBeanCopier.copy(userClientInfo, weiboUser, null);
                }else{
                    iterator.remove();
                    continue;
                }
            }else{
                BeanCopierUtil.UserClient2ThirdUserBeanCopier.copy(userClientInfo, weiboUser, null);
            }
            weiboUser.setProvince(queryVo.getProvinceId());
            weiboUser.setPassword(password);
            weiboUser.setUserName(userName);
            weiboUser.setImsi(userClientInfo.getImsi());
        }
        return weiboUsers;

    }


    /**
     * 如果没获取到的话 随机取一个用户
     * @param userName
     * @param carrier
     * @param provinceId
     * @return
     */
    private UserClientInfo selectRandomUser(String userName, Integer carrier, Integer provinceId){
        String cacheKey = CacheKey.WEIBO_USER_IMSI;
        String imsi = (String) redisClient.getHash(cacheKey, userName);
        QueryUserClientVo queryUserClientVo = new QueryUserClientVo();
        queryUserClientVo.setCarrier(carrier);
        queryUserClientVo.setProvince(provinceId);
        if(StringUtils.isNotBlank(imsi)){
            queryUserClientVo.setImsi(imsi);
            UserClientInfo userClientInfo = newClientInfoDao.selectClientInfo(queryUserClientVo);
            if(userClientInfo != null){
                return userClientInfo;
            }
        }else{
            UserClientInfo userClientInfo = newClientInfoDao.selectRandomClientInfo(queryUserClientVo);
            if(userClientInfo != null){
                redisClient.putHash(cacheKey, userName, userClientInfo.getImsi());
                return userClientInfo;
            }
        }
        return null;
    }



    /*
     * (non-Javadoc)
     *
     * @see
     * org.jsbd.boss.service.impl.AbsThirdUserServiceImpl#selectRetentTaskList()
     */
    @Override
    public List<MarkDayTask> selectRetentTaskList() {
        List<MarkDayTask> list = (List<MarkDayTask>) redisClient.get(CacheKey.WEIBO_TASK_DAY);
        if (list != null) {
            return list;
        } else {
            list = weiboUserDAO.selectRetentTaskList();
            if (list != null) {
                redisClient.put(CacheKey.WEIBO_TASK_DAY, list, DateUtil.leftTimeToMidNight() / 1000);
            }
        }
        return list;
    }



}
